//
//  ZFOAuthViewController.swift
//  WeiBo
//
//  Created by 左忠飞 on 2016/12/27.
//  Copyright © 2016年 左忠飞. All rights reserved.
//

import UIKit

///通过 webView 加载新浪微博授权界面
class ZFOAuthViewController: UIViewController {

    fileprivate lazy var webView = UIWebView()
    
    
    
    override func loadView() {
        view = webView
        
        //取消 webView 的滚动,新浪微博的服务器返回的页面默认就是全屏的
        webView.scrollView.isScrollEnabled = false
        
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        
        //设置代理
        webView.delegate = self

        
        //设置导航栏
        title = "登录新浪微博"
        
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 16, target: self, action: #selector(autoFille), isBack: false)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ///加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(ZFAppKey)&redirect_uri=\(ZFRedirectURI)"
        
        //1>确定要访问的资源
        guard let url = URL(string: urlString)
        
            else {
                
            return
            
        }
        
        //2>建立请求
        let request = URLRequest(url: url)
        
        //3>加载请求
        webView.loadRequest(request)
        
        
    }

   //  MARK: - 监听方法
    @objc fileprivate func close(){
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
        
    }
    
    
    ///自动填充, webView 的注入(直接通过 js 修改本地浏览器中缓存的内容)
    ///点击登录按钮,执行 submit(),将本地的数据提交到服务器
    
    @objc fileprivate func autoFille() {
        //准备 js
        let js = "document.getElementById('userId').value = '15210293945';"+"document.getElementById('passwd').value = 'feiaihua1314xl';"
        
        
        //让 webView 执行 js
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

extension ZFOAuthViewController:UIWebViewDelegate {
    
    
    /// webView 将要加载请求
    ///
    /// - Parameters:
    ///   - webView:  webView
    ///   - request:  要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载 request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //确认思路
        //如果请求地址包含回调的地址,不加载页面,否则加载页面
        
        if request.url?.absoluteString.hasPrefix(ZFRedirectURI) == false {
            return true
        }
        print("加载请求 --- \(request.url?.absoluteString)")
        
        //从回调地址的查询字符串中查找'code='
        //如果有,授权成功,否则,授权失败
        if request.url?.query?.hasPrefix("code=")  == false {
            print("取消授权")
            close()
            return false
        }
        
        //从 query 字符串中取出授权码
        //代码走到这里, URL 中一定包含"code"
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("取得授权码>>>>>>\(code)")
        
        //使用授权码获取 accesstoken
        ZFNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else{
                SVProgressHUD.showInfo(withStatus: "登录成功")
                //下一步做什么? 跳转界面 ? 使用通知,发送登录成功消息
                // 1 发送通知 -> 不关心有没有监听者,只负责发送
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZFUserLoginSuccessNotification), object: nil)
                // 2 关闭窗口
                self.close()
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
